/**
 * copyright (c) 2017-2022 厦门风领科技有限公司
 * http://www.fenglinghudong.com/
 * 
 * 声音管理.
 * Zy.
 * 2023-10-25.
 */

import { GGAudio } from "../../../framework/core/base/GGAudio";
import { GGResource } from "../../../framework/core/base/GGResource";
import { GGStore } from "../../../framework/core/base/GGStore";


export class AudioManager {

    private static _enable = null;
    private static _musicEnable = null
    private static isPreload = true;

    /** 开关. */
    public static set enable(v: boolean) {
        AudioManager._enable = v;
        GGStore.set("AudioEnable", v);
        AudioManager.preloadAudio();
    }
    public static get enable(): boolean {
        if (AudioManager._enable == null) {
            AudioManager._enable = GGStore.get("AudioEnable", true);
        }
        return AudioManager._enable;
    }
    

    /** 音乐开关. */
    public static set musicEnable(v: boolean) {
        AudioManager._musicEnable = v;
        GGStore.set("AudioMusicEnable", v);

        if (v == false) {
            GGAudio.stop()
            GGAudio.audioSource.volume = 0
        } else {
            AudioManager.playBackGroundMusic()
        }
    }
    public static get musicEnable(): boolean {
        if (AudioManager._musicEnable == null) {
            AudioManager._musicEnable = GGStore.get("AudioMusicEnable", true);
        }
        return AudioManager._musicEnable;
    }

    /** 预加载音频. */
    public static preloadAudio() {
        if (AudioManager.enable && AudioManager.isPreload) {
            AudioManager.isPreload = false;
            GGResource.loadBundle("audio").then(bundle => {
                if (bundle) {
                    bundle.loadDir("common");
                    bundle.loadDir("game");
                }
            });
        }
    }

    /** 播放按钮. */
    public static playButton() {
        AudioManager.playSound("audio:common/click");
    }

    /** 播放背景音乐. */
    public static playBackGroundMusic() {
        // AudioManager.playMuisc("audio:game/backgroup" + Math.floor( Math.random() * 8 ))
        AudioManager.playMuisc("audio:game/backgroup")
    }

    /** 播放闯关音乐. */
    public static playInGameMusic() {
        // AudioManager.playMuisc("audio:game/backgroup" + Math.floor( Math.random() * 8 ))
        AudioManager.playMuisc("audio:game/backgroup")
    }


    /** 播放音乐. */
    public static playMuisc(sound: string) {
        if (AudioManager.musicEnable) {
            GGAudio.play(sound);
        }
    }

    /** 播放音效. */
    public static playSound(sound: string) {
        return new Promise<any>((resolve) => {
            if (AudioManager.enable) {
                const value = GGAudio.playOneShot(sound);
                resolve(value);
                return;
            }
            resolve(null);
        });
    }

    public static stopCurrent() {
        GGAudio.stop()
    }

}
